//
//  QuickEditAmountView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 09.05.25.
//

import SwiftUI

struct QuickEditAmountView: View {
    
    @Environment(\.presentToast) var presentToast
    @Environment(\.presentationMode) var presentationMode;
    @StateObject var viewModel = QuickEditAmountViewModel()
    var detail: AccountingDetailCombine
    @State var preAmount: String = ""
    
    var body: some View {
        VStack {
            HStack (alignment: .center) {
                HStack (alignment: .center) {
                    CategoryIconView(item: viewModel.detail.category)
                    Text(viewModel.detail.getCategoryName())
                        .font(.system(size: 15))
                        .fontWeight(.medium)
                        .foregroundColor(Color.koiColorTitle)
                }
                
                Spacer()
                Text(viewModel.amount)
                    .font(.system(size: 28))
                    .foregroundColor(Color.koiColorPrimary)
                    .bold()
                    .fixedSize(horizontal: false, vertical: true)
            }
            .padding(EdgeInsets(top: 10, leading: 16, bottom: 10, trailing: 16))
            .background(Color.white.cornerRadius(16))
            .padding(EdgeInsets(top: 16, leading: 10, bottom: 0, trailing: 10))
            
            NumericKeypadView(
                numericClickCallback: { text in
                    viewModel.amount = text
                },
                doneClickCallback: {
                    viewModel.updateAmount()
                },
                reset: $viewModel.reset,
                preAmount: $preAmount
             )
            .frame(height: 264)
            .padding(10)
            .background(Color.koiColorBackgroundItem)
            .roundedCorner(16, corners: [.topLeft, .topRight])
        }
        .presentationBackground(Color.koiColorBackgroundItem)
        
        .onChange(of: viewModel.updateState) { value in
            if value == "" {
                return
            }
            if value == "success" {
                presentToast(.init(message: "修改成功"))
                KoiEvent.homeReload.send()
                presentationMode.wrappedValue.dismiss()
            } else {
                presentToast(.init(message: value))
            }
        }
        .onAppear {
            viewModel.detail = detail
            viewModel.amount = detail.getAmountNoSign()
            preAmount = viewModel.detail.detail.amount?.toStringWithoutTrailingZeros() ?? preAmount
        }
    }
}

#Preview {
    QuickEditAmountView(detail: AccountingDetailCombine.previewData())
}
